(This is part 2 of 3 of the Pocket Forth release 6.5 manual.)
Memory Management
In a Macintosh, certain conditions cause functional blocks of memory to move around(9). This is called memory management and is done by the memory manager in the ROM. (Brodie's fans: imagine a cartoon character for the manager.) Because of this, Macintosh programs must run from any memory location.
Memory available for a new program is allocated above the dictionary. Do not confuse this with addressable memory. Allocated memory is memory you are allowed to use by the memory manager. Addressable memory can be accessed with a relative address. Programs that alter memory should respect the limit of the allocated memory when using relative addressing. Pocket Forth comes with 32K (the maximum) allocated.
The dictionary is loaded from the disk as a 'DICT' resource. The entire dictionary can be written back to the disk with the word "save", replacing the previous DICT resource. This makes extensions and modifications a permanent part of your copy of Pocket Forth. NOTE: "save" cannot be undone.
The memory map, with high memory at the top:
figure 5
Other programs that may be in memory are not shown in this diagram.
Errors
Three types of error are reported: stack errors, numeric conversion errors and disk errors. All of these errors use the general purpose error word "abort". "Abort" prints a question mark, clears the file, parameter and return stacks and goes back to the prompt. A fourth type of error is not reported, the Apple Event error. See the Apple Event section for more details.
Stack errors occur when items are removed from the parameter stack when it is already empty. Since the parameter stack is often 'under flowed' this way, it is buffered so that no harm will be done by this condition. A stack error report looks like this: *?. Make a stack error happen by typing "drop" when you know the stack is empty.
Stack overflow on the other hand is not reported nor buffered. A runaway loop is the most often cause of stack overflow. The symptoms differ in each occurrence from a bomb box to extreme graphics and rude noises. Check your loops carefully.
Tokens not found in the dictionary are assumed to be numbers. If the conversion routine, "number", finds any characters greater than the value of "base", the token is not an integer either. Then the interpreter uses SANE to determine if the token is a valid floating point number. Usually these are numerals with a decimal point or an 'E', however, any undefined token beginning with a number is converted. Unconverted tokens are reported by printing the token in capital letters, then doing "abort". Type "xx" to see this error.
Disk errors are reported by printing "Disk:" and the number of the error encountered. Look up the error numbers in Inside Macintosh(10) or other text. "Abort" is executed after the message is printed.
Common disk errors include:
-35 No such volume error: disk name is misspelled or disk is not mounted.
-36 General purpose I/O error: cause unknown.
-43 File not found: pathname is misspelled or includes a space.
Use "abort" to write error handlers. Type a message then call "abort" as in this example:
: BASIC ( -- ) here 20 expect ( get a line of text )
." Syntax Error" abort ( report error and abort )
beep ; ( NOTE: this never happens )
Errors reported by some other Forth systems are not reported by Pocket Forth. Compiler or branching security is not provided, nor is free space checked before compiling. Multiple definitions of the same word are allowed. The lack of these messages can sometimes cause mysterious problems.
If the dictionary runs out of free space while compiling, compilation continues on, right into whatever is right after the DICT block in the heap. This is likely to cause a crash, so you must be aware of the memory available for your program. Remember to check free dictionary space with "room".
Toolbox
The toolbox is a collection of hundreds of routines within the ROM and System file that create the Macintosh interface. Pocket Forth enables use of the toolbox routines.
Toolbox routines are called by executing a 16 bit instruction called a trap word. Each routine has its own trap word that executes and returns as if it had been called as a subroutine. Compile trap words inline into Pocket Forth code.
A word ",$" (pronounced "comma hex") compiles a 16 bit hexadecimal number into the dictionary from the input stream. If the token after "comma hex" is not a hex number, a number conversion error is signaled. Use "comma hex" to compile trap words.
Most toolbox arguments are passed on the system stack. Because Pocket Forth's return stack is the system stack, return stack words can be used to setup for a toolbox call. The words ">r" and "2>r" move 16 and 32 bit values to the return stack. "R>" and "2r>" move 16 and 32 bit numbers from the return stack to the parameter stack. The word "a>r" performs a double duty: it converts a relative address on the stack to an absolute address which it pushes to the return stack.
To call a toolbox routine, setup the system stack with "a>r", ">r" and "2>r". If the toolbox call is a function, push a zero (single or double, as appropriate) to the return stack ahead of any arguments. Then compile the trap word with "comma-hex". Get function results with "r>" or "2r>". Examples of toolbox calls are in the example and extension programs and figure 6, below.
The operating system keeps information for its use in low memory global variables. These globals can be accessed using absolute addressing with the words "l@" and "dl@". See the definition of "ticks" in figure 6.
Machine Language
Machine code can be mixed with Forth code in definitions. Insert it as hex data directly with the word "comma hex". Be sure that all words execute correctly and end with an RTS instruction (use ";") or JMPs into another word's code field.
Respect the contents of most of the 680x0's registers. Save and restore registers that are used by Pocket Forth if you change them with machine code. The following table describes the register use:
Register Comments
D0-D1/A0-A1 Used and changed by many words; use freely
D2-D5 Preserved by all words; restore if used
D6.W Name address of the last definition (see "latest")
D7.W Input character counter
A2 (DP) Start of free memory absolute address (see "here")
A3 (BP) Base absolute address (see ">rel" and ">abs")
A4 (IS) The input stream pointer absolute address
A5 Macintosh operating system use
A6 (PS) The parameter stack pointer absolute address
A7 (RS) The return (and system) stack absolute address
The word "mon" executes the trap word _Debugger. If a debugger, such as TMON or MacsBug is installed, it is engaged, otherwise, the system bomb window appears. If it does, click the "Continue" (or "Resume") button to quit the application.
Here are examples of toolbox calls, global variables and machine language:
: 0>R ( return stack: -- 0 ) ( push a zero to the return stack )
,$ 4267 ; MACRO ( clr -[rs] )
: RANDOM ( -- u ) ( u is a random number, 0 to 65535 )
0>r ,$ A861 r> ; ( _Random )
: TICKS ( -- d ) ( double number = ticks since startup )
: CLS ( -- ) ( clear the window, leaving the cursor alone )
4 +md a>r ,$ A8A3 ; ( _EraseRect the window content rect )
And a memory diagram for these words:
figure 6
Events
Macintosh programs interact with users and other programs by means of 'events'. For example, clicking on a partially hidden window generates mouse down, mouse up, activate, deactivate and update events in order to bring the window to the front. Pocket Forth has default event handlers, so deal only with those that are pertinent.
The (relative) addresses of the event handlers are kept in a large table of unnamed variables. The addresses of the variables are calculated with the word "+md", which adds the address of the table to an offset. Some of the variables in the table hold other important data instead of handlers. You can customize Pocket Forth by changing the value of these variables.
Here is a list of the available variables. The left column's variables contain the addresses of routines. The right column contains handles, pointers, flags and other data.
Handler routines: Offset Other data: Offset
Activate window 12 Window Pointer 0
Update window 14 WRect, pixels 4
Button down 16 WSize, pixels 8
Idle 20 Menus list 18
Close 22 Screen echo flag 28
Version 24 AppleMenuHandle 30
Start up 26 File Menu Handle 34
Event routines: 116 Edit Menu Handle 38
(Button down) 118 File stack 42
(Button up) 120 Event record 148
(Key down) 122 What event 148
(Key up) 124 Message 150
(AutoKey) 126 When 154
(Update) 128 Where 158
(Disk inserted) 130 Modify 162
(Activate) 132 Selected window 164
(Apple Event) 136 Multitasking flag 186
(Multitask) 146 Apple Event list 188
Clicks: 168 Key pressed flag 192
inDeskRgn 168 Quit selected flag 194
inMenuRgn 170 Open ready flag 196
inSystemRgn 172 Apple Event reply 198
inContentRgn 174 Apple Event record 202
inDragRgn 176
inGrowRgn 178
inCloseRgn 180
inZoomIn 182
inZoomOut 184
Apple Event error 190
Routines:
• Activate expects a flag on the stack, true for window on, false for window off. The default handler is the word "drop". Substitute handler should also take a number off the stack.
• Update draws invalidated portions of the window if automatically invalidated by uncovering it or explicitly invalidated by a program. The default handler draws an underscore at the current text cursor position, and has no stack effect.
• Button executes when the mouse button is pressed inside the window. The word "beep" is the default handler. Handlers can make use of the words "@mouse" and "?button" to create more complex mouse button actions. The button handler has no stack effect.
• Idle is executed as often as possible, at least every 30th of a second. The default Idle handler does nothing, however, the idle routine is temporarily used by some Apple Events.
• Close executes in response to a click in the window's close box. The default handler executes "bye" which quits Pocket Forth.
• Version is a handler that identifies the version of the program running. The default handler displays the About… box from the Apple menu.
• Start up is executed when the program starts, after the window has been drawn, and all the registers are set up.
• Events is a list of first line handlers for the first 15 event types. These handlers do the behind the scene housekeeping for Pocket Forth. They execute the handlers described above and do not normally need to be modified. Apple events are mapped onto event number 10, the defunct network event.
• Clicks is a list of the various window part handlers. They handle desktop, menubar, desk accessory, window content region, drag region, grow box, close box, zoom in and zoom out region clicks. Modify these handlers to change the way the Pocket Forth window responds to mouse clicks in regions other than the content region.
• Apple Event error is executed if the result code of AEProcessAppleEvent is not zero. This allows other high level events to be handled. See the Apple Event section.
Data:
• Window contains a pointer to Pocket Forth's window. Get the window pointer with "0 +md 2@".
• WRect is the content rect of the window in local coordinates and WSize is the last four bytes of the rect, the width and height of the window. The values in wrect are used by "cr" and "page" and other routines.
• Menus is a variable that holds the relative address of a list of menu lists. See the menu section for an explanation.
• Screen echo is a variable that contains a flag. If the flag is true then text is shown when pasting or loading. If it's false then text display isn't done and loading (or pasting) is much faster. If the source code contains errors however, you will not be able to see where the error occurred unless the code is echoed.
• Apple Menu Handle, File Menu Handle and Edit Menu Handle are double variables that hold menu handles (absolute addresses) for the three built in menus.
• File stack is the memory to implement the stacks required to allow programs to load other programs. See the source code to discover the inner workings of the file stack.
• Event record holds the event record data. This is the record used by the main event loop. Since the system puts necessary data here, you should not modify these variables. Your event handlers should, however, test them.
• Selected window holds a temporary window pointer. Update and other routines use this variable, so it should not be changed.
• Multitasking flag contains true (-1) if a multitasking operating system such as System 7 or MultiFinder is in effect. A true flag indicates that trap WaitNextEvent is available and will retrieve events, if the flag is false, GetNextEvent is used instead.
• Apple Event list is a linked list of relative address pointers to the handlers for each apple event supported. The format of the list is: d.class d.message handler next.entry. The list is terminated with a zero for the next.entry field. Refer to the Apple Events section.
• Key pressed flag is used by the event loop. You should use the words "key" or "?terminal" to determine if a key is pressed.
• When the quit flag is set to any non zero value, the event loop exits Pocket Forth. Use the word "bye" to accomplish this.
• Open ready is true if a file is ready to be opened. The filename should be at 'pad' and a working directory number on the stack. This variable is used by "open", the 'odoc' handler and opening from the menu, but not by "-->".
• AEReply holds the handle to the reply Apple Event record, an empty apple event that is returned to the sending application. See the Apple Events section.
• AEEventRecord contains the handle to the current Apple Event data record. See the Apple Events section.
As mentioned above, none of these names are in the dictionary, but they can be defined as constants. Here are examples of the use of these variables:
12 +md constant ACTIVATE
14 +md constant UPDATE
16 +md constant BUTTON
24 +md constant VERSION
: MYACT ( flag -- ) IF ." Hello again!" cr THEN ; ( type the string )
: MYUPD ( -- ) 4 0 DO 8 emit LOOP .ok ( back up and issue prompt )
[ update @ compile ] ; ( call the original update handler )
: MYBUT ( -- ) version @ execute ; ( show version )
' myact activate ! ( set activate to address of "myact" )
' myupd update ! ( set 'update' to address of "myupd" )
' mybut button ! ( set 'button' to address of "mybut" )
Now try clicking on the window, hiding the window behind others, and re-selecting it.
More Variables
Other variables exist in the Pocket Forth dictionary, for use by the interpreter and other internal parts of the Pocket Forth system. These variables can also be used to patch Pocket Forth's actions. Unlike standard Forth user variables, these are unnamed.
Here is a list of the 'user' variables, the offsets are bytes from "tib".
Name Offset Description
TermBuf 0 terminal input buffer
StackSize 82 the size of the parameter stack, in bytes
IntA7 84 initial value of the system's stack pointer
Rzero 88 address of the bottom of the return stack
Szero 92 address of the bottom of the parameter stack
Form 96 decform record for floating point numbers
Expand 100 address of 'grow' routine in the CODE 1 resource
FreePt 104 relative address of the initial end of the dictionary
FreeSz 106 amount of free space at startup
DictPt 108 name address of the last word in the dictionary
NBase 110 value of the current number base at startup
Held 112 address for the next character in a numeral
DoesAdr 114 parameter from a created word for "does>"
fcolon 118 flag indicating the interpreter state (see "cstate")
fimmed 119 flag indicating an immediate word
fneg 120 flag indicating a negative number
fint 121 flag indicating input source (see "cblk")
fmacro 122 flag indicating macro compiling mode
fbit5 123 reserved flag
Menus
Menus can be created and changed. Three menus are already setup, Apple, File and Edit. You can add your own menus. Each menu (except the Apple Menu) consists of four parts: 1) A menu ID number, 2) a menu handle, 3) a menu handler list with an entry for each item in the menu and 4) a MENU resource. The menu resource is optional, as you may define menus from strings as well. MENU resources are much easier. See the Window&Menu example file.
Menu ID numbers apply to all of the application's menus. Menus are numbered 2 for the File menu and 3 for the Edit menu. Give new menus a number of 4 and higher if any are added. Handles for the existing menus are in the unnamed variables as shown in the table.
The order in the list of menu item handlers corresponds to the appearance of the items in the menu. The addresses of the menu handler lists from each menu (except the Apple menu) are kept in a list that looks like the menubar. This list of menu lists is pointed to by the Menus list unnamed variable (18 +md). Perhaps this picture of the menu handlers and pointers will clear things up:
figure 7
The Apple menu is handled separately because the only changeable item is About… which can be accessed via the Version unnamed variable.
To alter an item's handler, change the value of the handler in the menu's list to point to the word you want to run instead. To change an entire menu, change its address in the list of menus to point to a new list. This example sets the handler of the Clear item of the Edit menu to a word to clear the screen:
( Paste this example into Pocket Forth to try it out. )
18 +md @ ( get the contents of menus list variable )
2+ @ constant EMLIST ( address of the edit menu list )
' clear emlist 5 2 * + ! ( set item 5 {clear} to "clear" )
The menus included with Pocket Forth contain commands that facilitate interactive program development. The menu commands are:
Apple Menu
About Pocket Forth ... runs the handler routine whose address is kept in the variable at 24 +md. The default handler displays an alert box.
Desk accessories or Apple Menu Folder contents and the About item.
File Menu
Open ... presents a dialog box to choose a file to be opened. The chosen file is then loaded.
Save Dictionary ... presents a dialog asking you to confirm your choice. It does this because saving the dictionary cannot be undone. The dictionary is saved if you confirm the choice.
Debugger ... enters a machine language monitor by executing the word "mon". You must have a monitor program, such as TMON or MacsBug installed or the program will crash.
Print ... does nothing useful (it beeps).
Quit executes "bye".
Edit Menu
Undo, Cut, Copy and Clear do nothing except beep. They are provided to support desk accessories under ‘single’ Finder. See the example above to add a function to the Clear item.
Paste interprets the text on the clipboard.
Resources
Pocket Forth is entirely made out of resources. Here is a list of all of the resources in Pocket Forth:
TYPE ID bytes
actb 257 48 about alert color table
actb 258 48 red alert color table
aete 0 84 info about supported Apple Events *
ALRT 257 14 about box
ALRT 258 14 red (memory low) alert
ALRT 259 14 save alert
BNDL 128 36 finder icon bundle
cicn 128 970 color icon from about box
CODE 0 24 launching code
CODE 1 182 more launching code
DICT 257 6492 dictionary code
DITL 257 66 about box items list
DITL 258 90 red alert items list
DITL 259 154 save alert items list
FREF 128 7 finder reference for Pocket Forth
FREF 129 7 finder reference for text files
hdlg 257 50 about alert help balloon *
hdlg 259 82 save alert help balloon *
hfdr -5696 32 finder icon help balloon *
hmnu 1 40 apple menu help balloon *
hmnu 2 148 file menu help balloon *
hmnu 3 140 edit menu help balloon *
hrct 128 32 window help balloon rect definition *
hwin 128 30 window help balloon *
icl4 128 512 16 color icon *
icl8 128 1024 256 color icon *
ICN# 128 256 black and white icon
ICON 128 128 b&w icon for about box
ics# 128 64 small black and white icon
ics4 128 128 small 16 color icon *
ics8 128 256 small 256 color icon *
MENU 1 48 apple menu
MENU 2 104 file menu
MENU 3 72 edit menu
p4TH 0 38 signature and string for Get Info
PICT 128 352 picture for the about dialog
SIZE 1 10 multitasking and System 7 info
STR# 1 2384 help balloon text *
WIND 128 32 the main window
* used by System 7 only
To use resources in a program, create and install them into a copy of Pocket Forth. Use ResEdit or an equivalent program to do the resource surgery. The Window&Menu example shows a method for creating resources on the fly. The file ::Extensions:Misc includes a definition of RES to get a resource from an open file.
The DICT resource of Pocket Forth contains the dictionary code and data. A resource was used for the dictionary because of the simplicity of saving and modifying the data within it.